/* 
 * Copyright (c) 2009 Keith Lazuka
 * License: http://www.opensource.org/licenses/mit-license.html
 */

#import "KalView.h"
#import "KalGridView.h"
#import "KalLogic.h"
#import "KalPrivate.h"
#import "NavigationView.h"

#import "ActGlobal.h"
@implementation KalViewControllerCellWrapper
@synthesize cellAddress,cellPhoneNumber, cellAccessory;
-(id)initWithAddress:(NSString *)address andPhoneNumber:(NSString *)phoneNumber{
    self = [super init];
    if(self){
        cellPhoneNumber = phoneNumber;
        cellAddress = address;
        cellAccessory = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
        [cellAccessory setFont:[UIFont systemFontOfSize:10]];
    }
    return self;
}
-(void)dealloc{
    [cellAccessory release];
    [super dealloc];
}
@end

@interface KalView ()
- (void)addSubviewsToTitleView;
- (void)addSubviewsToContentView;
- (void) addSubviewsToButtonView;
- (void)addSubviewToSearchBar;
- (void)setHeaderTitleText:(NSString *)text;
@end

static const CGFloat kHeaderHeight = 44.f;
static const CGFloat kMonthLabelHeight = 17.f;

@implementation KalView

@synthesize delegate;
@synthesize _tableView = _tableView;
@synthesize tableData = _tableData;
- (id)initWithFrame:(CGRect)frame delegate:(id<KalViewDelegate>)theDelegate logic:(KalLogic *)theLogic
{
  if ((self = [super initWithFrame:frame])) {
    delegate = theDelegate;
    logic = [theLogic retain];
    [logic addObserver:self forKeyPath:@"selectedMonthNameAndYear" options:NSKeyValueObservingOptionNew context:NULL];
    self.autoresizesSubviews = YES;
    self.autoresizingMask = UIViewAutoresizingFlexibleHeight;
      //Navigation bar
      NavigationView *navigation = [[NavigationView alloc] initWithFrame:CGRectMake(0, 0, 320, kNavigationBarHeight)];
      [self addSubview:navigation];
      [navigation.btnBack setBackgroundImage:[UIImage imageNamed:@"backbar_button_root"] forState:UIControlStateNormal];
      [navigation.btnBack setUserInteractionEnabled:false];
      [navigation.btnRight1 addTarget:self action:@selector(doSetting:) forControlEvents:UIControlEventTouchUpInside];
      

      [navigation release];
      
      //title view for calendar
      _titleView = [[UIView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, kTitleViewWidth, kTitleViewHeigh)];
      [self addSubview:_titleView];
      [self addSubviewsToTitleView];
      
      //search view for production
      _searchView =[[UIView alloc] initWithFrame:_titleView.frame];
      [self addSubview:_searchView];
      [self addSubviewToSearchBar];
      
      
      
      //two buttons
      _buttonView = [[UIView alloc] initWithFrame:CGRectMake(0,kNavigationBarHeight + kTitleViewHeigh, kButtonViewWidth, kButtonViewHeigh)];
      [self addSubview:_buttonView];
      [self addSubviewsToButtonView];
      
      
      scrollView = [[[UIScrollView alloc] initWithFrame:CGRectMake(0.f,kNavigationBarHeight + kTitleViewHeigh+kButtonViewHeigh, frame.size.width, frame.size.height - (kNavigationBarHeight + kTitleViewHeigh+kButtonViewHeigh + kTabBarHeight))] autorelease];
      [scrollView setClipsToBounds:true];
      
      _contentView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height - (kNavigationBarHeight + kTitleViewHeigh+kButtonViewHeigh + kTabBarHeight))] autorelease];
      _contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
      [self addSubviewsToContentView];
      
      [scrollView setContentSize:CGSizeMake(_contentView.frame.size.width, _contentView.frame.size.height)];
      [scrollView addSubview:_contentView];
      [self addSubview:scrollView];
//      [self addSubview:_contentView];
      
      // The list of events for the selected day
      _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.f,kNavigationBarHeight+ kTitleViewHeigh+kButtonViewHeigh, frame.size.width, frame.size.height - (kTitleViewHeigh+kButtonViewHeigh+kNavigationBarHeight)) style:UITableViewStylePlain];
      _tableView.delegate=self;
      _tableView.dataSource=self;
      [_tableView setBackgroundColor:[UIColor clearColor]];
      _tableView.tableFooterView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
      _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
      [self addSubview:_tableView];
      [self performSelector:@selector(doSelectCalendar:)];
      
  }
  
  return self;
}

- (id)initWithFrame:(CGRect)frame
{
  [NSException raise:@"Incomplete initializer" format:@"KalView must be initialized with a delegate and a KalLogic. Use the initWithFrame:delegate:logic: method."];
  return nil;
}

- (void)redrawEntireMonth { [self jumpToSelectedMonth]; }

- (void)slideDown { [gridView slideDown]; }
- (void)slideUp { [gridView slideUp]; }

- (void)showPreviousMonth
{
  if (!gridView.transitioning)
    [delegate showPreviousMonth];
}

- (void)showFollowingMonth
{
  if (!gridView.transitioning)
    [delegate showFollowingMonth];
}
#pragma mark - add subviews
- (void)addSubviewsToButtonView{
    _calendarButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kButtonViewWidth/2, kButtonViewHeigh)];
    [_calendarButton addTarget:self action:@selector(doSelectCalendar:) forControlEvents:UIControlEventTouchUpInside];
    [_calendarButton setTitle:@"January" forState:UIControlStateNormal];
    [_calendarButton.titleLabel setFont:[UIFont boldSystemFontOfSize:14]];
    [_buttonView addSubview:_calendarButton];
    
    _productionButton = [[UIButton alloc] initWithFrame:CGRectMake(kButtonViewWidth/2, 0, kButtonViewWidth/2, kButtonViewHeigh)];
    [_productionButton addTarget:self action:@selector(doSelectProduction:) forControlEvents:UIControlEventTouchUpInside];
    [_productionButton setTitle:@"Production" forState:UIControlStateNormal];
    [_productionButton.titleLabel setFont:[UIFont boldSystemFontOfSize:14]];
    [_buttonView addSubview:_productionButton];
}
- (void)addSubviewToSearchBar{
    [_searchView setBackgroundColor:kMainTintColor];
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, _searchView.frame.size.width, _searchView.frame.size.height)];
    [searchBar setSearchTextPositionAdjustment:UIOffsetMake(33, 0)];
    [searchBar setBackgroundImage:[UIImage imageNamed:@"SearchBarBackground.png"]];
    [searchBar setImage:[UIImage imageNamed:@"SearchIcon.png"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    [searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"SearchFieldBackground.png"] forState:UIControlStateNormal];
    
    for (UIView *view in [searchBar subviews]){
        if ([view isKindOfClass:[UITextField class]]){
            [((UITextField *)view) setLeftViewMode:UITextFieldViewModeNever];
            [((UITextField *)view) setClearButtonMode:UITextFieldViewModeWhileEditing];
            
            self.lblSearchPlaceholder = [[[UILabel alloc] initWithFrame:CGRectMake(45, 0, 150, 44)] autorelease];
            [self.lblSearchPlaceholder setTextColor:[UIColor whiteColor]];
            [self.lblSearchPlaceholder setBackgroundColor:[UIColor clearColor]];
            [self.lblSearchPlaceholder setFont:UIFontSystem(14)];
            [self.lblSearchPlaceholder setText:@"Filter Results"];
            [self.lblSearchPlaceholder setHidden:false];
            [searchBar addSubview:self.lblSearchPlaceholder];
        }
    }
    [_searchView addSubview:searchBar];
    searchBar.delegate = self;
    [searchBar release];
}
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
}
- (void)addSubviewsToTitleView
{
    [_titleView setBackgroundColor:kMainTintColor];
  const CGFloat titleDayWidth = 46.0f;
  const CGFloat titleDayHeight = 30.0f;
  
  // Add column labels for each weekday (adjusting based on the current locale's first weekday)
  NSArray *weekdayNames = [[[[NSDateFormatter alloc] init] autorelease] shortWeekdaySymbols];
  NSArray *fullWeekdayNames = [[[[NSDateFormatter alloc] init] autorelease] standaloneWeekdaySymbols];
  NSUInteger firstWeekday = [[NSCalendar currentCalendar] firstWeekday];
  NSUInteger i = firstWeekday - 1;
  for (CGFloat xOffset = 0.f; xOffset < kTitleViewWidth; xOffset += 46.f, i = (i+1)%7) {
    CGRect weekdayFrame = CGRectMake(xOffset,kTitleViewHeigh-titleDayHeight-7, titleDayWidth, titleDayHeight);
    UILabel *weekdayLabel = [[UILabel alloc] initWithFrame:weekdayFrame];
    weekdayLabel.backgroundColor = [UIColor clearColor];
      weekdayLabel.font =[UIFont systemFontOfSize:14];//[UIFont boldSystemFontOfSize:10.f];
    weekdayLabel.textAlignment = UITextAlignmentCenter;
      weekdayLabel.textColor = [UIColor whiteColor];//[UIColor colorWithRed:0.3f green:0.3f blue:0.3f alpha:1.f];
    weekdayLabel.shadowColor = [UIColor whiteColor];
    weekdayLabel.shadowOffset = CGSizeMake(0.f, 1.f);
    weekdayLabel.text = [weekdayNames objectAtIndex:i];
    [weekdayLabel setAccessibilityLabel:[fullWeekdayNames objectAtIndex:i]];
    [_titleView addSubview:weekdayLabel];
    [weekdayLabel release];
  }
}

- (void)addSubviewsToContentView
{
  // Both the tile grid and the list of events will automatically lay themselves
  // out to fit the # of weeks in the currently displayed month.
  // So the only part of the frame that we need to specify is the width.
  CGRect fullWidthAutomaticLayoutFrame = CGRectMake(0.f, 0.f, self.width, 0.f);
    
    // The tile grid (the calendar body)
  gridView = [[KalGridView alloc] initWithFrame:fullWidthAutomaticLayoutFrame logic:logic delegate:delegate];
  [gridView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:NULL];
    [gridView setDelegate:self];
  [_contentView addSubview:gridView];
    
  
  // Trigger the initial KVO update to finish the contentView layout
  [gridView sizeToFit];
}

-(void) changeCalendarBottomViewWithDate:(NSString *)date name:(NSString *)name volume:(NSString *)volume company:(NSString *)company{
    if (!_bottomCalendarView){
        _bottomCalendarView = [[UIView alloc] initWithFrame:CGRectMake(0.f, _contentView.height, self.width, 100)];
        [_bottomCalendarView setBackgroundColor:[UIColor clearColor]];
        [scrollView addSubview:_bottomCalendarView];
        [scrollView setContentSize:CGSizeMake(self.width, _contentView.height + _bottomCalendarView.height)];
    }
    if (!lblDate){
        lblDate = [[[UILabel alloc] initWithFrame:CGRectMake(15, 15, 250, 30)] autorelease];
        [lblDate setFont:UIFontSystem(20)];
        [lblDate setTextColor:[UIColor darkGrayColor]];
        [lblDate setBackgroundColor:[UIColor clearColor]];
        [_bottomCalendarView addSubview:lblDate];
    }
    [lblDate setText:date];
    
    if (!lblName){
        lblName = [[[UILabel alloc] initWithFrame:CGRectMake(15, 43, 150, 15)] autorelease];
        [lblName setFont:UIFontSystem(12)];
        [lblName setTextColor:[UIColor lightGrayColor]];
        [lblName setBackgroundColor:[UIColor clearColor]];
        [_bottomCalendarView addSubview:lblName];
    }
    [lblName setText:name];
    
    if (!lblVolume){
        lblVolume = [[[UILabel alloc] initWithFrame:CGRectMake(120, 43, 150, 15)] autorelease];
        [lblVolume setFont:UIFontSystem(12)];
        [lblVolume setTextColor:[UIColor lightGrayColor]];
        [lblVolume setBackgroundColor:[UIColor clearColor]];
        [_bottomCalendarView addSubview:lblVolume];
    }
    [lblVolume setText:volume];
    
    if (!lblCompany) {
        lblCompany = [[[UILabel alloc] initWithFrame:CGRectMake(15, 58, 120, 13)] autorelease];
        [lblCompany setFont:UIFontSystem(9)];
        [lblCompany setTextColor:[UIColor lightGrayColor]];
        [lblCompany setBackgroundColor:[UIColor clearColor]];
        [_bottomCalendarView addSubview:lblCompany];
    }
    [lblCompany setText:company];
    
    if (!imgButton){
        imgButton = [[[UIImageView alloc] initWithFrame:CGRectMake(265, 25, 40, 40)] autorelease];
        [imgButton setImage:[UIImage imageNamed:@"payment_selection_icon"]];
        [_bottomCalendarView addSubview:imgButton];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
  if (object == gridView && [keyPath isEqualToString:@"frame"]) {
    
    /* Animate tableView filling the remaining space after the
     * gridView expanded or contracted to fit the # of weeks
     * for the month that is being displayed.
     *
     * This observer method will be called when gridView's height
     * changes, which we know to occur inside a Core Animation
     * transaction. Hence, when I set the "frame" property on
     * tableView here, I do not need to wrap it in a
     * [UIView beginAnimations:context:].
     */
    CGFloat gridBottom = gridView.top + gridView.height;
    CGRect frame = _bottomCalendarView.frame;
    frame.origin.y = gridBottom;
    frame.size.height = _bottomCalendarView.superview.height - gridBottom;
   _bottomCalendarView.frame = frame;
    shadowView.top = gridBottom;
    
  } else if ([keyPath isEqualToString:@"selectedMonthNameAndYear"]) {
    [self setHeaderTitleText:[change objectForKey:NSKeyValueChangeNewKey]];
    
  } else {
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  }
}
#pragma mark - main buttons
-(void)doSelectCalendar:(id)sender{
    _contentView.hidden = NO;
    _titleView.hidden = NO;
    scrollView.hidden = false;
    
    _tableView.hidden = YES;
    _searchView.hidden = YES;
    [_calendarButton setBackgroundImage:[UIImage imageNamed:@"calendar_button_selected"] forState:UIControlStateNormal];
    [_productionButton setBackgroundImage:[UIImage imageNamed:@"production_button"] forState:UIControlStateNormal];
}

-(void)doSelectProduction:(id)sender{
//    _titleView
    _contentView.hidden=YES;
    _titleView.hidden = YES;
    scrollView.hidden = true;
    _tableView.hidden = NO;
    _searchView.hidden = NO;
    [_calendarButton setBackgroundImage:[UIImage imageNamed:@"calendar_button"] forState:UIControlStateNormal];
    [_productionButton setBackgroundImage:[UIImage imageNamed:@"production_button_selected"] forState:UIControlStateNormal];
    
}
#pragma mark - navigation bar buttons
- (void)doBackButton:(id)sender{
    
}

-(void) doSetting:(id) sender{
    [self.delegate btnSettingClicked];
}
#pragma mark - others
- (void)setHeaderTitleText:(NSString *)text
{
//  [headerTitleLabel setText:text];
//  [headerTitleLabel sizeToFit];
//  headerTitleLabel.left = floorf(self.width/2.f - headerTitleLabel.width/2.f);
}

- (void)jumpToSelectedMonth {
    [gridView jumpToSelectedMonth];
}

- (void)selectDate:(KalDate *)date {
    [gridView selectDate:date];
}

- (BOOL)isSliding {
    return gridView.transitioning;
}

- (void)markTilesForDates:(NSArray *)dates {
    [gridView markTilesForDates:dates];
}

- (KalDate *)selectedDate {
    return gridView.selectedDate;
}

- (void)dealloc
{
  [logic removeObserver:self forKeyPath:@"selectedMonthNameAndYear"];
  [logic release];
    [_titleView release];
    [_searchView release];
    [_productionButton release];
    [_calendarButton release];
    [_buttonView release];
    [_bottomCalendarView release];
    [_contentView release];
    [_tableView release];
//  [headerTitleLabel release];
  [gridView removeObserver:self forKeyPath:@"frame"];
  [gridView release];
  [shadowView release];
  [super dealloc];
}
#pragma mark - table view
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString* identifier = @"Cell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell){
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];
        [cell.textLabel setFont:[UIFont systemFontOfSize:14]];
        [cell.detailTextLabel setFont:[UIFont systemFontOfSize:10]];
        UIView *background = [[UIView alloc] initWithFrame:cell.frame];
        [background setBackgroundColor:kSelectionColor];
        cell.selectedBackgroundView = background;
        [background release];
    }
    if(indexPath.row < _tableData.count){
        KalViewControllerCellWrapper *celldata = [_tableData objectAtIndex:indexPath.row];
        cell.textLabel.text = celldata.cellAddress;
        cell.detailTextLabel.text = celldata.cellPhoneNumber;
        cell.accessoryView = celldata.cellAccessory;
    }
    
    return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _tableData.count;
}

#pragma mark - UISearchBarDelegate Methods Implementation
-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
}

-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if ([searchBar.text isEqualToString:@""]){
        [self.lblSearchPlaceholder setHidden:false];
    }
    else{
        [self.lblSearchPlaceholder setHidden:true];
    }
}

#pragma mark - KalGridViewDelegate Methods Implementation
-(void) gridViewClickedAtDate:(KalDate *)date{
    if ([date day] == 7){
        [self changeCalendarBottomViewWithDate:@"January 7, 2013"name:@"Nixon Watch Commercial" volume:@"" company:@"Nixon Watch Company"];
    }
    else if ([date day] == 10){
        [self changeCalendarBottomViewWithDate:@"January 10, 2013" name:@"Modern Family" volume:@"Seasion 1, Episode 10" company:@"20th Century Fox"];
    }
    else if ([date day] == 25){
        [self changeCalendarBottomViewWithDate:@"January 25, 2013" name:@"Modern Family" volume:@"Season 1, Episode 12" company:@"20th Century Fox"];
    }
}
@end
